<template>
  <div class="student-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>Student Management</span>
          <div class="search-container">
            <el-input
                v-model="searchQuery"
                placeholder="Search students..."
                class="search-input"
                clearable
                @input="handleSearch"
            >
              <template #suffix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSearch">Search</el-button>
          </div>
        </div>
      </template>

      <el-table
          :data="filteredStudents"
          border
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="name" label="Name" width="120" />
        <el-table-column prop="studentId" label="Username" width="140" />
        <el-table-column prop="email" label="Email" width="180" />
        <el-table-column prop="phone" label="Phone" width="140" />
        <el-table-column label="Status" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'warning'">
              {{ scope.row.status === 'active' ? 'Active' : 'Inactive' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="120">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewStudentDetails(scope.row)">
              <el-icon><View /></el-icon>Details
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalStudents"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Student Details Dialog -->
    <el-dialog
        v-model="detailsDialogVisible"
        title="Student Details"
        width="60%"
        destroy-on-close
    >
      <el-descriptions
          v-if="currentStudent"
          :column="2"
          border
      >
        <el-descriptions-item label="Name">{{ currentStudent.name }}</el-descriptions-item>
        <el-descriptions-item label="Username">{{ currentStudent.studentId }}</el-descriptions-item>
        <el-descriptions-item label="Phone">{{ currentStudent.phone }}</el-descriptions-item>
        <el-descriptions-item label="Email">{{ currentStudent.email }}</el-descriptions-item>
        <el-descriptions-item label="Status">
          <el-tag :type="currentStudent.status === 'active' ? 'success' : 'warning'">
            {{ currentStudent.status === 'active' ? 'Active' : 'Inactive' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailsDialogVisible = false">Close</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import {
  Search,
  View
} from '@element-plus/icons-vue';
import { getStudents, getStudentDetail } from '../../api/student';
import type { Student } from '../../api/user';
import { useRouter } from 'vue-router';

// State variables
const loading = ref<boolean>(false);
const searchQuery = ref<string>('');
const currentPage = ref<number>(1);
const pageSize = ref<number>(10);
const totalStudents = ref<number>(0);
const students = ref<Student[]>([]);
const currentStudent = ref<Student | null>(null);
const detailsDialogVisible = ref<boolean>(false);
const router = useRouter();

// Initialize data
onMounted(() => {
  fetchStudents();
});

// Fetch student data
const fetchStudents = async () => {
  loading.value = true;
  try {
    const data = await getStudents();
    students.value = data;
    totalStudents.value = data.length;
    ElMessage.success('Successfully retrieved student data');
  } catch (error) {
    console.error('Failed to retrieve student data:', error);
    ElMessage.error('Failed to retrieve student data, please try again later');
  } finally {
    loading.value = false;
  }
};

// Filter students based on search query
const filteredStudents = computed(() => {
  if (!searchQuery.value) return students.value;

  const query = searchQuery.value.toLowerCase();
  return students.value.filter(student =>
      student.name?.toLowerCase().includes(query) ||
      student.studentId?.toLowerCase().includes(query) ||
      student.email?.toLowerCase().includes(query)
  );
});

// Handler functions
const handleSearch = () => {
  currentPage.value = 1;
};

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  currentPage.value = 1;
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
};

const viewStudentDetails = async (student: Student) => {
  try {
    loading.value = true;
    // Get student details
    const detailedStudent = await getStudentDetail(student.id);
    currentStudent.value = detailedStudent;
    detailsDialogVisible.value = true;
  } catch (error) {
    console.error('Failed to retrieve student details:', error);
    ElMessage.error('Failed to retrieve student details');
  } finally {
    loading.value = false;
  }
};

// Helper functions
const percentFormat = (percentage: number): string => {
  return percentage ? `${percentage}%` : '0%';
};

const getProgressColor = (completion: number): string => {
  if (completion >= 80) return '#67C23A';
  if (completion >= 50) return '#409EFF';
  return '#E6A23C';
};

const getActivityType = (type: string): string => {
  switch (type) {
    case 'success': return 'success';
    case 'warning': return 'warning';
    case 'error': return 'danger';
    default: return 'primary';
  }
};
</script>
<style scoped>
.student-management {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.details-tabs {
  margin-top: 20px;
}

.mt-4 {
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 